<?php

namespace App\Supports\Payment\Methods\Adawxmini;

use Brick\Math\RoundingMode;
use App\Supports\Payment\Methods\Method;
use App\Supports\Payment\Contracts\MethodPay;
use Illuminate\Validation\ValidationException;

class PayVip extends Method implements MethodPay
{
	public function validate($purchase = null)
	{
		if ($purchase->isPaid()) {
			fail('目标订单已支付');
		}
		if ($purchase->isClosed()) {
			fail('目标订单已关闭');
		}
		if ($purchase->isCancelled()) {
			fail('目标订单已取消');
		}
	}
	
	public function info($purchase = null)
	{
		$orderNo = 'vip_'.$purchase->number;
		$title = '支付有点东西订单: ' . $purchase->number;
		$payAmt = big_decimal($purchase->total_amount)->toScale(2, RoundingMode::HALF_UP);
		
		return [
			'adapay_func_code' => 'wxpay.createOrder',
			'app_id' => ($this->channel->config())['app_id'],
			'order_no' => $orderNo,
			'pay_amt' => $payAmt,
			'goods_title' => $title,
			'goods_desc' => $title,
			'notify_url' => route('web.payments.adapay.notify'),
		];
	}
	
	public function pay($purchase = null)
	{
		$this->validate($purchase);
		
		try {
			
			$info = $this->info($purchase);
			
			$pay = $this->channel->pay($info);
			
			if ($pay->isError()) {
				throw ValidationException::withMessages(['err' => $pay->result['error_msg']]);
			} else {
				$result = $pay->result['expend'];
				return [
					'g_id' => $result['g_id'],
					'path' => $result['path'],
					'pre_order_id' => $result['pre_order_id'],
					'scheme_code' => $result['scheme_code'],
					'wx_h5_pay_url' => $result['wx_h5_pay_url'],
				];
			}
		} catch (Exception $exception) {
			return fail('支付暂不可用!');
		}
	}
}
